<template>
	<div class="w-100 row-ac-jc" :style="'height:' + documentHeight + 'px;'">
		<div class="login-box p-20">
			<div class="flex-1 row-ac-jc font-s-18 font-w pb-20">Welcome back</div>
			<div class="flex-1">
				<input type="text" class="input-box" placeholder="username" v-model="username" />
			</div>
			<div class="flex-1 mt-20">
				<input type="password" class="input-box" placeholder="password" v-model="password" />
			</div>
			<div class="mt-20">
				<div class="login-button row-ac-jc cursor-pointer" @click="handleLogin">login</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		useRouter
	} from 'vue-router'
	import {
		useToken
	} from '@/composables/useToken'

	const {
		post,
		get,
		patch
	} = useFetchApi();

	const {
		getToken,
		setToken,
		clearToken
	} = useToken()


	const router = useRouter()
	const loginStatus = ref(false)
	const documentHeight = ref(0)
	const username = ref('')
	const password = ref('')

	const updateHeight = () => {
		documentHeight.value = window.innerHeight
	}

	onMounted(async () => {
		updateHeight()
		window.addEventListener('resize', updateHeight)
		const token = getToken();
		if (token) {
			loginStatus.value = true
		} else {
			loginStatus.value = false
		}
	})

	const handleLogin = async () => {
		try {
			const res = await post('/api/login', {
				username: username.value,
				password: password.value
			});
			if (res.code === 200) {
				setToken(res.data.access_token);
				// ✅ 登录成功后跳转
				const redirect = router.currentRoute.value.query.redirect;
				if (redirect) {
					// 如果是从守卫重定向来的，跳回原路径
					router.push(redirect);
				} else {
					// 否则默认跳到后台首页
					router.push('/admin');
				}
			} else {
				console.error("登录失败：", res);
			}
		} catch (error) {
			console.error('Login failed:', error);
		}
	};

	onUnmounted(() => {
		window.removeEventListener('resize', updateHeight)
	})
</script>

<style>
	.login-box {
		width: 320px;
		background-color: #f5f5f5;
		border-radius: 2px;
	}

	.input-box {
		width: 310px;
		padding: 10px 5px;
		border-radius: 2px;
	}

	.login-button {
		width: 310px;
		height: 32px;
		background-color: black;
		color: #fff;
	}
</style>